const {watchFile} = require("./fileWatch");

function uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function safeParseJson(str) {
    try {
        return JSON.parse(str)
    } catch (e) {
        return null
        console.error('转换json失败', str)

    }
}


const codeContanst = require('./codeContanst')

const net = require('net');
const port = 11111;
const hostname = '127.0.0.1';

// 定义两个变量， 一个用来计数，一个用来保存客户端
let clients = {};
let clientName = 0;

var ws = require("nodejs-websocket");
console.log("开始建立连接...")

var connectMap = {}
var conectWatchFileMap = {}
var server = ws.createServer(function (conn) {
    //客户端连接 就会在这里新生成一个 conn
    var _uuid = uuid()
    conn._uuid = _uuid
    connectMap[_uuid] = conn
    //新生成一个conn 就给客户端发送一个uuid
    conn.sendText(JSON.stringify({uuid: uuid(), code: codeContanst.code_init}));
    //监听接送事件
    conn.on("text", function (str) {
        var messageObj = safeParseJson(str)
        //普通的文本消息
        if (messageObj.code == codeContanst.code_message) {
            console.log("普通的文本消息", messageObj.message)
        }
        /*
        * @desc 收到监听文件请求
        * 开始监听文件
        * */
        if (messageObj.code == codeContanst.code_file_watch) {
            conectWatchFileMap[messageObj.uuid] &&
            conectWatchFileMap[messageObj.uuid].unwatch &&
            conectWatchFileMap[messageObj.uuid].unwatch();

            conectWatchFileMap[conn._uuid] &&
            conectWatchFileMap[conn._uuid].stopWatch &&
            conectWatchFileMap[conn._uuid].stopWatch();

            var fileName = messageObj.fileName
            var watchFileConnect = watchFile(fileName, (lastLineStr) => {
                //文件改变   最后一行
                conn.sendText(JSON.stringify({
                    code: codeContanst.code_file_change_message,
                    message: lastLineStr,
                    uuid: messageObj.uuid
                }))
            })
            conectWatchFileMap[messageObj.uuid] = watchFileConnect
        }
    })
    conn.on("close", function (code, reason) {
        console.log("关闭连接", conn._uuid, code, reason)
        //文件监听系统停止监听 tail.unwatch()
        conectWatchFileMap[conn._uuid] &&
        conectWatchFileMap[conn._uuid].unwatch &&
        conectWatchFileMap[conn._uuid].unwatch();
        conectWatchFileMap[conn._uuid] &&
        conectWatchFileMap[conn._uuid].stopWatch &&
        conectWatchFileMap[conn._uuid].stopWatch();

    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭", code, reason)
    });
}).listen(11111)
console.log("websoket in ", 11111)
